#!/usr/bin/env python
import os
import sys
import win32ras

def Connect(rasEntryName, numRetries = 5):
     for info in win32ras.EnumConnections():
         if info[1] == rasEntryName:
             print "Already connected to '%s'" % (rasEntryName,)
             return 1
     dial, have_pw = win32ras.GetEntryDialParams(None, rasEntryName)
     if not have_pw:
         print "Error: The password is not saved for this connection"
         print "Please connect manually selecting the 'save password' option and try again"
         sys.exit(1)
     retryCount = numRetries
     bValid = 0
     print "Connecting to:", rasEntryName
     while retryCount > 0:
         rasHandle, errCode = win32ras.Dial(None, None, dial, None)
         if win32ras.IsHandleValid(rasHandle):
             bValid = 1
             break
         print "Retrying..."
         win32api.Sleep(5000)
         retryCount = retryCount - 1
     return bValid

def FixRoute():
     data = os.popen("ipconfig", "r").readlines()
     have_ppp = 0
     ip_str = None
     for line in data:
         if line.startswith("PPP"):
             have_ppp = 1
         if have_ppp and line.strip().startswith("IP Address"):
             ip_str = line.split(":")[1].strip()

     if ip_str is None:
         print "ERROR: could not find the PPP ip address"
     else:
         print "Your PPP IP address is", ip_str
         cmd = "route add 192.168.2.0 mask 255.255.255.0 %s" % (ip_str,)
         print cmd
         os.system(cmd)
         print "Route updated."

if len(sys.argv) == 2:
     if not Connect(sys.argv[1]):
         print "Could not connect to '%s'" % (sys.argv[1],)
         sys.exit(1)
         FixRoute()
else:
     print "Usage: python.exe %s host_ip" % (sys.argv[0],)		
	 
